var user = require('../../static/js/user.js');
var util = require('../../static/js/util.js');
var api = require('../../static/js/api.js');
var app = getApp();

Page({
  data: {
    userInfo: {},
    hasMobile: '',
    stepInfoList: [],
    sportsCoin:0.88
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数
    var that = this;
    user.loginByWeixin().then(res => {
      console.log(res)
      var sessionKey = res.session_key
      //2、调用小程序API: wx.getWeRunData获取微信运动数据（加密的）；
      wx.getWeRunData({
        success(resRun) {
          user.decryRunData(resRun, sessionKey).then(res => {
            res.stepInfoList = res.stepInfoList.reverse()
            for (var i in res.stepInfoList) {
              //给数据加上时间，格式呢，在你的util.js下面写，建微信小程序项目的时候就有，import进来就行，不要也可以
              res.stepInfoList[i].date = util.formatTime(new Date(res.stepInfoList[i].timestamp * 1000))
            }
            that.setData({
              stepInfoList: res.stepInfoList
            });
          })
        }
      })
    })
  },
  onReady: function() {

  },
  onShow: function() {

    let userInfo = wx.getStorageSync('userInfo');
    let token = wx.getStorageSync('token');

    // 页面显示
    if (userInfo && token) {
      app.globalData.userInfo = userInfo;
      app.globalData.token = token;
    }

    this.setData({
      userInfo: app.globalData.userInfo,
    });

  },
  onHide: function() {
    // 页面隐藏

  },
  onUnload: function() {
    // 页面关闭
  },

  bindGetUserInfo: function(e) {
    wx.setStorageSync('userInfo', e.detail.userInfo);
    this.setData({
      'userInfo': wx.getStorageSync('userInfo'),
      'token': wx.getStorageSync('token')
    })

    user.loginByWeixin(e.detail).then(res => {
      app.globalData.userid = res.data.userid;
      wx.setStorageSync('userid', res.data.userid);
    }).catch((err) => {
      console.log(err)
    });
  },

  exitLogin: function() {
    wx.showModal({
      title: '',
      confirmColor: '#b4282d',
      content: '退出登录？',
      success: function(res) {
        if (res.confirm) {
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          wx.switchTab({
            url: '/pages/index/index'
          });
        }
      }
    })

  }
})